package com.fyzk.activity;

import android.arch.lifecycle.ViewModelProviders;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.util.TypedValue;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.bumptech.glide.Glide;
import com.fyzk.activity.app.ActivityTaskManager;
import com.fyzk.activity.app.AppToast;
import com.fyzk.activity.fragment.BetDetailsFragment;
import com.fyzk.activity.fragment.DocumentaryUserFragment;
import com.fyzk.activity.fragment.RankListFragment;
import com.fyzk.activity.indicator.ScaleTransitionPagerTitleView;
import com.fyzk.activity.lottery.recommend_order.IndicatorBean;
import com.fyzk.activity.lottery.recommend_order.MyRecommendBean;
import com.fyzk.activity.lottery.recommend_order.MyRecommendOrderBean;
import com.fyzk.activity.lottery.recommend_order.OtherCenterActivity;
import com.fyzk.activity.user.LoginActivity;
import com.fyzk.adapter.BluePrintDetailsAdapter;
import com.fyzk.adapter.DocumentaryPagerAdapter;
import com.fyzk.base.BaseActivity;
import com.fyzk.bean.DocumentaryMenuResponse;
import com.fyzk.data.AppLotteryInfos;
import com.fyzk.data.preference.MySharedPreferences;
import com.fyzk.model.BluePrintDetailsViewModel;
import com.fyzk.net.Commands;
import com.fyzk.utils.AppUtil;
import com.fyzk.utils.AssetsUtil;
import com.fyzk.utils.CheckClickUtils;
import com.fyzk.utils.DensityUtils;
import com.fyzk.utils.IntentParamUtils;
import com.fyzk.utils.SpanUtils;
import com.fyzk.view.TabLayoutUnderline;
import com.fyzk.view.TopTitleView;
import com.fyzk.view.ViewCallBack;
import com.tyjc.lottery.R;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.SimplePagerTitleView;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.util.DensityUtil;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;

import http.Common.CommandUtil;
import http.DataUtil.text.TextUtil;
import http.StringResultBean;

//方案详情页面
@ContentView(R.layout.activity_blue_print_details)
public class BluePrintDetailsActivity extends BaseActivity {
    @ViewInject(R.id.ttv_blue_print_details)
    TopTitleView mTtvBluePrintDetails;
    @ViewInject(R.id.mMagicIndicator)
    MagicIndicator mMagicIndicator;
    @ViewInject(R.id.blue_print_details_vp)
    ViewPager mVpBluePrintDetails;
    @ViewInject(R.id.iv_avatar)
    ImageView mIvAvatar;
    @ViewInject(R.id.tv_username)
    TextView mTvUserName;
    @ViewInject(R.id.tv_fans)
    TextView mTvFans;
    @ViewInject(R.id.tv_attention)
    ImageView mIvAttention;
    @ViewInject(R.id.tv_score_a_hit)
    TextView mTvScoreAHit;
    @ViewInject(R.id.tv_hit_profits)
    TextView mTvHitProfits;
    @ViewInject(R.id.tv_award)
    TextView mTvAward;
    @ViewInject(R.id.tv_number)
    TextView mTvNumber;
    @ViewInject(R.id.ll_recently_info)
    LinearLayout mLlRecentlyInfo;
    @ViewInject(R.id.tv_recently_hit_profits)
    TextView mTvRecentlyHitProfits;
    @ViewInject(R.id.tv_lottery_type_name)
    TextView mTvLotteryTypeName;

    private BluePrintDetailsAdapter mAdapter;
    private List<Fragment> mTabFragment = new ArrayList<>();
    private List<DocumentaryMenuResponse> mTabNameList;
    private String mUserNo;
    private int mIsAttention = 2;//是否已关注


    private MyRecommendOrderBean mInfo;
    private BluePrintDetailsViewModel mBluePrintDetailsViewModel;

    @Override
    public void initViews() {
        super.initViews();
        mUserNo = getIntent().getStringExtra(IntentParamUtils.USERNO);
        mInfo = (MyRecommendOrderBean) getIntent().getSerializableExtra(IntentParamUtils.RECOMMENDINFOR);
        mInfo.setUserno(mUserNo);
        if (null != mInfo)
            mTvLotteryTypeName.setText(mInfo.getLotteryTypeName());
        mIvAttention.setVisibility(isSelf() ?
                View.GONE : View.VISIBLE);
        mTtvBluePrintDetails.setOnTitleClickListener(this);
        mTtvBluePrintDetails.getBackView().setImageResource(R.drawable.icon_back_white);
        mIvAvatar.setOnClickListener(this);
        mIvAttention.setOnClickListener(this);
        mBluePrintDetailsViewModel = ViewModelProviders.of(this).get(BluePrintDetailsViewModel.class);
        String mTabName = AssetsUtil.read(this, "json/bluePrintDetailsTab.json");
        mTabNameList = JSON.parseObject(mTabName, new TypeReference<List<DocumentaryMenuResponse>>() {
        });

        if (null != mInfo){
            for (DocumentaryMenuResponse menuResponse : mTabNameList) {
                if (menuResponse.getId() == 2){//跟单用户
                    menuResponse.setName(String.format("%s(%s人)",
                            menuResponse.getName(),
                            mInfo.getFollowCount()));
                }
            }
        }

        initIndicator();
        loadHeadData(true);
    }

    /**
     * 是否是自己
     * @return
     */
    private boolean isSelf() {
        return TextUtils.equals(MySharedPreferences.getInstance().getUserNo(), mUserNo);
    }

    private void initIndicator() {
        CommonNavigator commonNavigator = new CommonNavigator(getContext());
        commonNavigator.setAdjustMode(true);
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {
            @Override
            public int getCount() {
                return mTabNameList.size();
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {
                SimplePagerTitleView simplePagerTitleView = new ScaleTransitionPagerTitleView(context);
                simplePagerTitleView.setNormalColor(context.getResources().getColor(R.color.race_color_1c));
                simplePagerTitleView.setSelectedColor(context.getResources().getColor(R.color.race_color_tab_text_color));
                simplePagerTitleView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 17);
                simplePagerTitleView.setText(mTabNameList.get(index).getName());
                simplePagerTitleView.setOnClickListener(v -> mVpBluePrintDetails.setCurrentItem(index));
                return simplePagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                LinePagerIndicator linePagerIndicator = new LinePagerIndicator(context);
                linePagerIndicator.setMode(LinePagerIndicator.MODE_EXACTLY);
                linePagerIndicator.setStartInterpolator(new AccelerateInterpolator());
                linePagerIndicator.setEndInterpolator(new DecelerateInterpolator(1.6f));
                linePagerIndicator.setLineWidth(DensityUtil.dip2px(36));
                linePagerIndicator.setLineHeight(DensityUtil.dip2px(2));
                linePagerIndicator.setRoundRadius(DensityUtil.dip2px(2));
                linePagerIndicator.setColors(context.getResources().getColor(R.color.race_color_tab_text_color));
                return linePagerIndicator;
            }
        });
        mMagicIndicator.setNavigator(commonNavigator);

        mTabFragment.add(BetDetailsFragment.newInstance(mInfo,mUserNo));
        mTabFragment.add(DocumentaryUserFragment.newInstance(mInfo));
        mAdapter = new BluePrintDetailsAdapter(getSupportFragmentManager(), mTabNameList, mTabFragment);
        mVpBluePrintDetails.setAdapter(mAdapter);

        ViewPagerHelper.bind(mMagicIndicator, mVpBluePrintDetails);
    }

    /**
     * 加载顶部网络数据
     */
    private void loadHeadData(boolean isShowProgress) {
        JSONObject request_json = new JSONObject();
        try {
            request_json.put("userno", mUserNo);
            httpPostJson(CommandUtil.FINDRECOMMENDEDRANKUSERDETAIL, Commands.FINDRECOMMENDEDRANKUSERDETAIL, request_json,
                    isShowProgress);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onSuccess(int requestCode, StringResultBean resultBean, String result) {
        super.onSuccess(requestCode, resultBean, result);
        switch (requestCode) {
            case CommandUtil.FINDRECOMMENDEDRANKUSERDETAIL:
                MyRecommendBean mUserInfo = JSON.parseObject(resultBean.getData(), MyRecommendBean.class);
                initData(mUserInfo);
                break;
            case CommandUtil.USERFOLLOWER:
                if (1 == mIsAttention) {
                    AppToast.getToast().show("取消成功");
                    mIvAttention.setImageResource(R.drawable.icon_attention_god);
                    mIsAttention = 2;
                    notifyAttentionNum(false);
                } else {
                    AppToast.getToast().show("关注成功");
                    mIvAttention.setImageResource(R.drawable.icon_yet_attention_god);
                    mIsAttention = 1;
                    notifyAttentionNum(true);
                }
                break;
        }
    }

    @Override
    protected void onFailure(int requestCode, String message) {
        super.onFailure(requestCode, message);
        switch (requestCode) {
            case CommandUtil.FINDRECOMMENDEDRANKUSERDETAIL:
                break;
            case CommandUtil.USERFOLLOWER:
                if (1 == mIsAttention) {
                    AppToast.getToast().show("取消失败");
                } else {
                    AppToast.getToast().show("关注失败");
                }
                break;
        }
    }

    @Override
    protected void onFailure(int requestCode, String errorCode, String message) {
        super.onFailure(requestCode, errorCode, message);
        switch (requestCode) {
            case CommandUtil.FINDRECOMMENDEDRANKUSERDETAIL:
                break;
            case CommandUtil.USERFOLLOWER:
                if (1 == mIsAttention) {
                    AppToast.getToast().show("取消失败");
                } else {
                    AppToast.getToast().show("关注失败");
                }
                break;
        }
    }

    private void initData(MyRecommendBean mUserInfo) {
//        String recentStatus = "近期状态：" + mUserInfo.getTotalCount() + "中" + mUserInfo.getWinCount();
//        Spannable spannable = new SpannableString(recentStatus);
//        spannable.setSpan(new AbsoluteSizeSpan((int) DensityUtils.sp2px(getResources(), 15)), 0, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//        spannable.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.color_111111)), 0, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//        spannable.setSpan(new ForegroundColorSpan(Color.parseColor("#fffd4a4a")), 5, recentStatus.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        mTvUserName.setText(mUserInfo.getUserName());

        setRecentlyInfoText(mTvAward, "中奖彩金", AppUtil.formatToYuanLXS(mUserInfo.getTotalWinAmount() / 100) + "米");
        setRecentlyInfoText(mTvScoreAHit, "命中率", AppUtil.formatToYuanLXS(mUserInfo.getHitRatio() * 100) + "%");
        setRecentlyInfoText(mTvHitProfits, "盈利率", AppUtil.formatToYuanLXS(mUserInfo.getProfitRatio() * 100) + "%");
        setRecentlyInfoText(mTvNumber, "带红人数", mUserInfo.getBeltRedCount());
//        mTvScoreAHit.setText(AppUtil.formatToYuanLXS(mUserInfo.getHitRatio() * 100) + "%");
//        mTvHitProfits.setText(AppUtil.formatToYuanLXS(mUserInfo.getProfitRatio() * 100) + "%");
//        mTvAward.setText(AppUtil.formatToYuanLXS(mUserInfo.getTotalWinAmount() / 100) + "米");
//        mTvNumber.setText(mUserInfo.getBeltRedCount() + "人");

        mLlRecentlyInfo.setVisibility(View.GONE);
        mTvRecentlyHitProfits.setVisibility(View.VISIBLE);
        SpanUtils.with(mTvRecentlyHitProfits)
                .appendLine(AppUtil.formatToYuanLXS(mUserInfo.getProfitRatio() * 100) + "%")
                .setForegroundColor(getResources().getColor(R.color.color_fe4a4b))
                .setFontSize(30, true)
                .append("近15天盈利")
                .setForegroundColor(getResources().getColor(R.color.color_999999))
                .setFontSize(13, true)
                .create();

        String mFansStr = "粉丝：" + mUserInfo.getFollowCount();
        mTvFans.setText(mFansStr);
        mIsAttention = mUserInfo.getStatus();
        if (1 == mIsAttention) {
            mIvAttention.setImageResource(R.drawable.icon_yet_attention_god);
        } else {
            mIvAttention.setImageResource(R.drawable.icon_attention_god);
        }
        Glide.with(this)
                .load(mUserInfo.getUserPhotoUrl())
                .circleCrop()
                .error(R.drawable.rr_header_icon)
                .placeholder(R.drawable.rr_header_icon)
                .into(mIvAvatar);
    }

    private void setRecentlyInfoText(TextView textView, String title, String content) {
        SpanUtils.with(textView)
                .appendLine(content)
                .setForegroundColor(getResources().getColor(R.color.color_fe4a4b))
                .setFontSize(16, true)
                .append(title)
                .setForegroundColor(getResources().getColor(R.color.color_999999))
                .setFontSize(12, true)
                .create();
    }

    @Override
    public void onClick(View arg0) {
        super.onClick(arg0);
        Intent intent;
        switch (arg0.getId()) {
            case R.id.iv_avatar://进入个人中心
                intent = new Intent(getContext(), OtherCenterActivity.class);
                if (!TextUtil.isEmpty(mUserNo)) {
                    intent.putExtra(IntentParamUtils.USERNO, mUserNo);
                    startActivity(intent);
                }
                break;
            case R.id.tv_attention:
                if (!CheckClickUtils.isFastClick()) {
                    if (MySharedPreferences.getInstance().getLoginStatus()) {
                        if (mIsAttention == 1) {
                            sendAttentionOrCancelAttentionGod(2);
                        } else {
                            sendAttentionOrCancelAttentionGod(1);
                        }
                    } else {
                        AppLotteryInfos.clear();
                        ViewCallBack.getInstance().countDownObjs.clear();
                        ActivityTaskManager.getInstance().closeAllActivity();
                        intent = new Intent(getContext(), LoginActivity.class);
                        startActivity(intent);
                    }
                }
                break;
        }
    }

    /**
     * 关注或者取消关注大神
     *
     * @param isAttention 1关注  2取关
     */
    private void sendAttentionOrCancelAttentionGod(int isAttention) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("userno", MySharedPreferences.getInstance().getUserNo());
            jsonObject.put("followerUserno", mUserNo);
            jsonObject.put("status", isAttention);
            httpPostJson(CommandUtil.USERFOLLOWER, Commands.USERFOLLOWER, jsonObject, true);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 刷新关注数
     *
     * @param isPlus 是加1还是减1
     */
    private void notifyAttentionNum(boolean isPlus) {
        if (null == mTvFans) {
            return;
        }
        String mFans = mTvFans.getText().toString();
        if (mFans.length() > 3) {
            String mFansNum = mFans.substring(3);
            if (mFansNum.length() < 1) {
                return;
            }
            int mIntFansNum = Integer.valueOf(mFansNum);
            if (isPlus) {
                mIntFansNum++;
            } else {
                if (mIntFansNum > 0) {
                    mIntFansNum--;
                }
            }
            String mFansStr = "粉丝：" + mIntFansNum;
            mTvFans.setText(mFansStr);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (1001 == requestCode) {
            loadHeadData(false);
            if (null == mBluePrintDetailsViewModel) {
                return;
            }
            mBluePrintDetailsViewModel.onRequestRefreshLogin(mInfo);
        }
    }

    @Override
    protected int getStatusBarColor() {
        return R.color.color_fe4a4b;
    }
}
